﻿
/*---------------------使用方法 ---------------------------
    
    <body onload="init()">
        <input type="text" id="test_calendar" /> 
        <button onclick="calendarName.show ('test_calendar','测试标题');" >测试按钮</button>
        <div id="div_calendar" style="display:none"></div> 
    </body>
    
    定义页面控件
    var calendarName;
    function init() {  //在[body]的onload事件调用
        calendarName=new Calendar("div_calendar","calendarName");
        calendarName.init();
    }
    
    在[按钮]的onClick事件 调用 calendarName.show();具体如下:
    //显示日历
    calendarName.show ("test_calendar","测试标题");
    或者
    calendarName.show2("test_calendar",$(test_calendar),"测试标题",0);
    或者
    calendarName.show2("test_calendar",$(test_calendar).value,"测试标题",1); 
    
    //*******
    在 window.onresize=function () { 
            calendarName.setDivPos();  //可以调整日历的相对位置
    }
 */
 
//判断是否IE
function isIE()
{ 
    return !(window.navigator.appName.toLowerCase().indexOf('explorer') == -1);
}
//取控件对象
function $(elementId) {
    if (document.getElementById) {
        return document.getElementById(elementId);
    }
    else if (document.all) {
        return document.all[elementId];
    }
    else return null;
}

function Calendar(divName,selftName) { 
    var calendar=this;
    this.currentDate =new Date();
    this.currentYear =this.currentDate.getFullYear();
    this.currentMonth=this.currentDate.getMonth() +1;
    this.currentDate  =this.currentDate.getDate(); 
    this.divObj=$(divName);  
    this.targetObj; 
    this.MaxYear=2099;
    this.MinYear=1949; 
 
    var name=selftName;//日历的名字

    //初始化,
    this.init=function (){
        var str='<div style="width: 200px;">\n\n'+
        '<table cellpadding="0" cellspacing="0" style="width:99%;border-collapse:collapse;">\n'+
            '<thead style="background-color:#f0f0f0;">\n'+
                '<tr  style="height:20px;">\n'+
                    '<td style="'+setBorder(1,0,1,0,"center",12)+' vertical-align:middle;width:15px;">\n'+
                       '<button  style="width:15px;height:20px;"onclick="'+name+'.hidden();'+name+'.clearObjTime();return false;" title="清空日历">x</button>\n'+
                    '</td>\n'+
                    '<td style="'+setBorder(1,0,1,0,"center",12)+'">\n'+
                        '选择日期[<span style="color:Red;" id="identity_title">日期</span>]\n'+
                    '</td>\n'+
                    '<td style="'+setBorder(1,0,0,1,"center",12)+' vertical-align:middle;width:15px;">\n'+
                       '<button  style="width:15px;height:20px;"onclick="'+name+'.hidden();return false;" title="关闭日历">x</button>\n'+
                    '</td>\n'+
                '</tr>\n'+
            '</thead>\n'+
        '</table>\n'+
        '<table cellpadding="0" cellspacing="0" style="width:99%;border-collapse:collapse;background-color:#f0f0f0;">\n'+
            '<tbody>\n'+
                '<tr>\n'+
                    '<td style="width:80px;height:20px;padding:0px 0px 0px 0px;'+setBorder(0,0,1,0,"center",12)+'">\n'+
                        '<select id="obj_month" onchange="'+name+'.changeMonth();" style="width:80px;height:18px;">\n'+
                            '<option value="1">一月</option>\n'+
                            '<option value="2">二月</option>\n'+
                            '<option value="3">三月</option>\n'+
                            '<option value="4">四月</option>\n'+
                            '<option value="5">五月</option>\n'+
                            '<option value="6">六月</option>\n'+
                            '<option value="7">七月</option>\n'+
                            '<option value="8">八月</option>\n'+
                            '<option value="9">九月</option>\n'+
                            '<option value="10">十月</option>\n'+
                            '<option value="11">十一月</option>\n'+
                            '<option value="12">十二月</option>\n'+
                        '</select>\n'+
                    '</td>\n'+
                    '<td style="width:80px;height:20px;'+setBorder(0,0,0,0,"center",12)+'"> <input type="text"  id="obj_year"  maxlength="4" style="width:70px;height:20px;" value="2006" readonly="true"/></td>\n'+
                    '<td style="width:15px;height:20px;'+setBorder(0,0,0,0,"center",12)+'"> <button style="width:15px;height:20px;" onclick="'+name+'.decreaseYear();return false;" title="上一年">&lt;</button></td>\n'+
                    '<td style="width:15px;height:20px;'+setBorder(0,0,0,1,"center",12)+'"> <button style="width:15px;height:20px;" onclick="'+name+'.addYear();return false;" title="下一年">&gt;</button></td>\n'+
                '</tr>\n'+
            '</tbody>\n'+
        '</table> \n'+
        '<table cellpadding="0" cellspacing="0" style="width:99%;border-collapse:collapse;">\n'+
            '<tbody  id= "day_list_tbody"    style="background-color:#f2f2f2;"> </tbody> \n'+
        '</table> \n'+
        '<table cellpadding="0" cellspacing="0" style="width:99%;border-collapse:collapse;">\n'+
            '<tfoot style="background-color:#f0f0f0;" >\n'+
                '<tr style="height:20px;">\n'+
                    '<td colspan="7" style="'+setBorder(0,1,1,1,"center",12)+'"></td>\n'+
                '</tr>\n'+
            '</tfoot>\n'+
        '</table>\n'+
        '</div>';
        this.divObj.innerHTML=str;
        $("obj_month").value=this.currentMonth;
        $("obj_year").value=this.currentYear; 
        this.drawtBody(); 
    } 
    //显示日历
    this.show=function (targetObjName,title, bGetMonth) {
        this.targetObj=$(targetObjName);
        if(this.targetObj==null)    return;  
        if(title==null || title.length==0)  
            $("identity_title").style.display="none";
        else  
            this.cellInsertText($("identity_title"),title) ;  
		
		this.m_bGetMonth = bGetMonth == null ? false : true;  //是否只获取月份
        this.setCurrentDateTime();
        this.drawtBody();
        this.setDivPos();
        this.divObj.style.display="block";
    } 
    //显示日历2
    //tag=0 表示是参数targetObjValue的值是目标对象的value  
    //tag=1 表示是参数targetObjValue是日期   
    this.show2=function (targetObjName,targetObjValue,title,tag) {
        this.targetObj=$(targetObjName); 
        if(this.targetObj==null)    return;
        var datetime_str="";
        if(tag==0) { 
            datetime_str=this.targetObj.value;
        } else if(tag==1) {
            datetime_str=targetObjValue;
        } 
        if(title==null || title.length==0)  
            $("identity_title").style.display="none";
        else  
            this.cellInsertText($("identity_title"),title) ;   
        if(datetime_str==null || judge_datetime_format(datetime_str)==false || judge_datetime(datetime_str)==false) {
            this.setCurrentDateTime();
        } else { 
            var date=datetime_str.split('-');  
            var year=date[0]*1;
            var month=date[1]*1;
            var date= date[2]*1;    
            this.setDateTime(year,month,date);     
        }  
        this.drawtBody();
        this.setDivPos();  //设置div的位置
        this.divObj.style.display="block"; 
    } 
    //设置日历显示的位置(当window窗体改变大小时，调用此方法重新计算日历)
    this.setDivPos=function () {  
        var left=0;
        var top=0;
        var pos=getObj_Pos(calendar.targetObj);
        if(pos !=null) {  
             left=pos[0]+"px";
             top=pos[1]+ pos[3]+"px";
         }
        this.divObj.style.position  ="absolute"; 
        this.divObj.style.left =left;
        this.divObj.style.top  =top;   
    }
    //画表格 
    this.drawtBody=function () {
        var year    = this.currentYear;
        var month   = this.currentMonth;
        var day     = this.currentday;  
        var tbody=$("day_list_tbody");
        if(tbody==null) return;
        while(tbody.rows.length>0)
            tbody.deleteRow(0); 
        var array=new Array("日","一","二","三","四","五","六");
        var tRow=tbody.insertRow(0);
        var tCell; 
        tCell=this.drawCell(tRow,0,array[0]); 
        tCell.style.backgroundColor="#F9CFD9"; 
        for(var a_i=1;a_i<7;a_i++) {
            tCell=this.drawCell(tRow,a_i,array[a_i]); 
        } 
        var firstDay=this.getFirstDay(year,month);//第一天为星期几 
        var monthSize=this.getDaysSize(year,month);//天数 
        var n=0;
        for(var i=0;i<6;i++) {
            tRow=tbody.insertRow(tbody.rows.length);
            for(var j=0;j<7;j++) {
                n++;
                if(n>firstDay&&n<=monthSize+firstDay) { 
                    tCell=this.drawCell(tRow,j,n-firstDay);
                    this.setCellStyle(tCell);
                    if(this.currentDate==n-firstDay) { 
                        tCell.style.color="blue";
                    }  
                }else {
                    this.drawCell(tRow,j," ");
                }
            }
        } 
    }
    //画格子
    this.drawCell=function (tRow,index,text) {
        var tCell=tRow.insertCell(index);
        this.cellInsertText(tCell,text); 
        tCell.style.cssText="border:solid 1px black;height:20px;text-align:center;font-size:12px";
        return tCell;
    }
    //设置格子样式 和 鼠标事件
    this.setCellStyle=function(tCell) { 
        tCell.style.backgroundColor="buttonface"; 
        tCell.onmouseover=function(){
            tCell.style.backgroundColor="#FfF0F0"; 
            if(isIE()==true)
                tCell.style.cursor="hand";
        }
        tCell.onmouseout=function(){
            tCell.style.backgroundColor="buttonface";
        } 
        tCell.onmouseup=function(){
            tCell.style.backgroundColor="buttonface";
        }     
        tCell.onclick=function(){ 
			if(!calendar.judgeSelectMonth()) //判断是否选择月份返回
			{
				if(calendar.targetObj){
					var day;
					if(isIE()==true) day=tCell.innerText;
					else             day=tCell.textContent; 
					calendar.targetObj.value= currentSelectDateTime(day);
				}
			}
            calendar.hidden();
        }
    }
    //清零,设为当前系统日期
    this.setCurrentDateTime=function () {
        this.currentDate =new Date();
        this.currentYear =this.currentDate.getFullYear();
        this.currentMonth=this.currentDate.getMonth() +1;
        this.currentDate  =this.currentDate.getDate();
        
        $("obj_month").value=this.currentMonth;
        $("obj_year").value=this.currentYear;         
    } 
    //设置日期
    this.setDateTime=function (year,month,date) {
        this.currentDate =new Date(year,month,date);
        this.currentYear =this.currentDate.getFullYear();
        this.currentMonth=this.currentDate.getMonth() ;
        this.currentDate  =this.currentDate.getDate();
        
        $("obj_month").value=this.currentMonth;
        $("obj_year").value=this.currentYear;         
    } 
    //当前选择的日期
    function currentSelectDateTime(day) {
        var year=calendar.currentYear;
        var month=calendar.currentMonth<=9?("0"+calendar.currentMonth):calendar.currentMonth;
        var date= day<=9?("0"+day):day;
        return ( year+"-"+ month +"-"+ date); 
    }     
	//当前选择的月份
    function currentSelectMonth() {
        var year=calendar.currentYear;
        var month=calendar.currentMonth<=9?("0"+calendar.currentMonth):calendar.currentMonth;
        return ( year+"-"+ month); 
    } 
	//判断是否选择月份返回
    this.judgeSelectMonth=function () {
		if(this.m_bGetMonth)
		{
            this.targetObj.value= currentSelectMonth();
            calendar.hidden();
			return true;
		}
		return false;
    } 
    //关闭
    this.hidden = function () { 
        calendar.divObj.style.display="none";
    }
    //年+
    this.addYear =function () {
        this.currentYear++; 
        if(this.currentYear>this.MaxYear)
            this.currentYear=this.MinYear;
        $("obj_year").value=this.currentYear;
        this.drawtBody();
    }
    //年-
    this.decreaseYear=function () {
        this.currentYear--;
        if(this.currentYear<this.MinYear)
            this.currentYear=this.MaxYear;
        $("obj_year").value=this.currentYear;
        this.drawtBody();
    }
    //月+/-
    this.changeMonth=function () {
        this.currentMonth=$("obj_month").value;
        this.drawtBody();
		this.judgeSelectMonth(); //判断是否选择月份返回
    } 
    //表格写文本
    this.cellInsertText=function (cell,value) {
        if(isIE() ==true)
           { cell.innerText=value; return cell.innerText;}
        else
           { cell.textContent=value;   return cell.textContent;}     
    }
    //日期格式应该为 2005-01-01
    function judge_datetime_format(datetime_str) {
        var regu = "^([0-9]{4}-[0-9]{1,2}-[0-9]{1,2})$";
        var re = new RegExp(regu);
        if (datetime_str.search(re)  == -1)   
            return false; //格式不正确 
        else 
            return true;
    }
    //日期是否正确   
    function judge_datetime(datetime_str) {
        var date=datetime_str.split('-');
        if(date==null || date.length<3)     return false;
        var year=date[0]*1;
        var month=date[1]*1;
        var day= date[2]*1;
        var numDays=new Array(31,28,31,30,31,30,31,31,30,31,30,31);
        if(month > 12 || month <= 0 || day > 31 || day <= 0) return false;
        if(month==2&&((year%4==0)&&(year%100!=0)||(year%400==0))) {     //润年
             if(day>29) return false;
        } else  if(day >numDays[month-1]) return false;   //非润年
        return true;
    }  
    //取得每月天数，判断平年闰年
    this.getDaysSize=function (year,month) {
        var numDays=new Array(31,28,31,30,31,30,31,31,30,31,30,31);
        var n=numDays[month-1];
        if(month==2&&((year%4==0)&&(year%100!=0)||(year%400==0))) n=29; //闰年
        return n;
    }
    //取得月份的第一天为星期几 (返回0表示星期天)
    this.getFirstDay=function(theYear, theMonth){
        var firstDate = new Date(theYear,theMonth-1,1);
        return firstDate.getDay();
    } 
    //取得对象的绝对位置
    function getObj_Pos(e) {  
        if(e==null) return;
        var t=e.offsetTop; 
        var l=e.offsetLeft; 
        var w=e.offsetWidth;
        var h=e.offsetHeight;
        var pos=new Array();
        while(e=e.offsetParent){ 
            t+=e.offsetTop; 
            l+=e.offsetLeft; 
         }
        pos[0]=l;
        pos[1]=t;
        pos[2]=w;
        pos[3]=h;
        return pos;
    } 
    
    //设置表格的线条
    var setBorder=function (top,bottom,left,right,textalign,fontsize) {
        var csstext="border-top:solid "+top+"px black; border-bottom:solid "+bottom+"px black; border-left:solid "+left+"px black; border-right:solid "+right+"px black;text-align:"+textalign+";font-size:"+fontsize+"px";
         return csstext;
    }
    //清空对象的时间
    this.clearObjTime=function () { 
        calendar.targetObj.value= "";
    }
}